# coding=utf-8
from __future__ import print_function, absolute_import
import sys, time, datetime
from gm.api import *

def init(context):
    # 订阅浦发银行, bar频率为一天和一分钟
    # 指定数据窗口大小为50
    # 订阅订阅多个频率的数据，可多次调用subscribe
    #subscribe(symbols='SHSE.600000', frequency='1d', count=50)
    subscribe(symbols='SHSE.600000', frequency='5s', count=50, wait_group=True, wait_group_timeout='10s')

    #algo(p_context=context)


def on_bar(context, bars):
    # context.data提取缓存的数据滑窗, 可用于计算指标
    # 注意：context.data里的count要小于或者等于subscribe里的count
    data = context.data(symbol=bars[0]['symbol'], frequency='60s', count=50, fields='close,bob')
    # 打印最后5条bar数据（最后一条是最新的bar）
    print(data.tail())

def algo(p_context=None):

    index_socre(p_factor=100, p_index_code='SHSE.000016', p_start_time='2021-05-19', p_end_time='2021-05-19')

    pass


def index_socre(p_factor=100, p_index_code='SHSE.000016', p_start_time=None, p_end_time=None):
    """
    指数强于深证成指大于0，MAX10 (特定的指数和深证成指比较)
    上证50 / 沪深300 / 中证500 / 创业板 / 科创50

    # SZSE.399001   深证成指 NOTE
    # SHSE.000016	上证50
    # SHSE.000300	沪深300
    # SHSE.000905	中证500
    # SZSE.399006	创业板指
    # NOTE 000688   科创50

    :param p_factor:
    :param p_index_code:
    :param p_start_time:
    :param p_end_time:
    :return:
    """

    history_data_of_SZSE_399001 = history(symbol='SZSE.399001', frequency='1d', start_time=p_start_time,
                                          end_time=p_end_time,
                                          fields='open, close, low, high, eob, price', adjust=ADJUST_PREV, df=True)
    history_data_of_x = history(symbol=p_index_code, frequency='1d', start_time=p_start_time,
                                end_time=p_end_time,
                                fields='open, close, low, high, eob, price', adjust=ADJUST_PREV, df=True)
    gap = history_data_of_x.loc[0, 'open'] - history_data_of_SZSE_399001.loc[0, 'open']

    rst = float(p_factor/100)*10 if gap > 0 else 0

    return rst


if __name__ == '__main__':
    p_strategy_id = sys.argv[1].split('=')[1] if len(sys.argv) > 1 else '__invalid__strategy_id'
    p_token = sys.argv[2].split('=')[1] if len(sys.argv) > 2 else '__invalid__token'

    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id=p_strategy_id,
        filename='main.py',
        mode=MODE_BACKTEST,
        token=p_token,
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)